package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.TrafficOneHourPageViewBean;
import com.atguigu.realtime.bean.TrafficPageViewBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
/**
 * @auther yuzehua
 * @date 2022/10/26 - 19:37
 */
public class Dws_TrafficOneHourPageViewWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_TrafficOneHourPageViewWindow().init(
                2012,
                2,
                "Dws_TrafficOneHourPageViewWindow",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1.封装成一个POJO
        SingleOutputStreamOperator<TrafficOneHourPageViewBean> beanStream = parseToPojo(stream);
        // 2.开窗聚合
        SingleOutputStreamOperator<TrafficOneHourPageViewBean> resultStream = windowAndAgg(beanStream);
        // 3. 写出到 clickhouse 中
        writeToClickhouse(resultStream);
    }

    private void writeToClickhouse(SingleOutputStreamOperator<TrafficOneHourPageViewBean> resultStream) {
        resultStream
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_one_hour_page_view_window",
                        TrafficOneHourPageViewBean.class
                ));
    }

    private SingleOutputStreamOperator<TrafficOneHourPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficOneHourPageViewBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(WatermarkStrategy.
                        <TrafficOneHourPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner(new SerializableTimestampAssigner<TrafficOneHourPageViewBean>() {
                            @Override
                            public long extractTimestamp(TrafficOneHourPageViewBean element, long recordTimestamp) {
                                return element.getTs();
                            }
                        })
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TrafficOneHourPageViewBean>() {
                    @Override
                    public TrafficOneHourPageViewBean reduce(TrafficOneHourPageViewBean value1, TrafficOneHourPageViewBean value2) throws Exception {
                        value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                        value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                        value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                        return value1;
                    }
                }, new ProcessAllWindowFunction<TrafficOneHourPageViewBean, TrafficOneHourPageViewBean, TimeWindow>() {
                    @Override
                    public void process(Context context, Iterable<TrafficOneHourPageViewBean> elements, Collector<TrafficOneHourPageViewBean> out) throws Exception {
                        TrafficOneHourPageViewBean bean = elements.iterator().next();
                        Long svCt = bean.getSvCt();
                        if (svCt != 0){
                            bean.setAvgPvCt(bean.getPvCt() / svCt);
                        } else {
                            bean.setAvgPvCt(bean.getPvCt());
                        }

                        bean.setStt(AtguiguUtil.toDatTime(context.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDatTime(context.window().getEnd()));
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                });
    }

    private SingleOutputStreamOperator<TrafficOneHourPageViewBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, TrafficOneHourPageViewBean>() {

                    private ValueState<String> hourState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        // 给状态设置ttl
                        ValueStateDescriptor<String> desc = new ValueStateDescriptor<>("hourState", String.class);
                        desc.enableTimeToLive(new StateTtlConfig.Builder(org.apache.flink.api.common.time.Time.hours(1)).build());
                        hourState = getRuntimeContext().getState(desc);
                    }

                    @Override
                    public TrafficOneHourPageViewBean map(JSONObject obj) throws Exception {

                        JSONObject common = obj.getJSONObject("common");
                        JSONObject page = obj.getJSONObject("page");

                        Long ts = obj.getLong("ts");

                        Long pvCt = 1L;

                        long svCt = 0L;
                        String lastPageId = page.getString("last_page_id");
                        if (lastPageId == null || lastPageId.length() == 0) {
                            svCt = 1L;
                        }

                        Long uvCt = 0L;
                        // 状态中存储年月日小时, 如果来的数据和状态不一样, 就是次小时的第一条数据，则uvCt=1 更新状态,
                        // 否则就不是第一条
                        String date = hourState.value();
                        String hour = AtguiguUtil.toDateHour(ts);
                        //System.out.println(hour);
                        if (!hour.equals(date)) {
                            // 更新状态
                            hourState.update(hour);
                            uvCt = 1L;
                        }

                        return new TrafficOneHourPageViewBean(
                                "","",uvCt,svCt,pvCt,0L,ts
                        );
                    }
                });
    }
}
